package com.guisu.animation.loading.multi_shape_loading

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.view.View
import kotlin.math.sqrt

class ShapeView: View {

    private var mCurrentShape = Shape.Circle
    private val mPaint by lazy { Paint(Paint.ANTI_ALIAS_FLAG) }
    private val mPath by lazy { Path() }

    enum class Shape {
        Circle, Triangle, Square
    }

    constructor(context: Context): this(context, null)
    constructor(context: Context, attributeSet: AttributeSet?): this(context, attributeSet, 0)
    constructor(context: Context, attributeSet: AttributeSet?, defStyleAttr: Int): super(context, attributeSet, defStyleAttr) {
        initData(context, attributeSet)
    }

    private fun initData(context: Context, attributeSet: AttributeSet?) {
        mPaint.style = Paint.Style.FILL
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        // 保证是正方形
        val width = MeasureSpec.getSize(widthMeasureSpec)
        val height = MeasureSpec.getSize(heightMeasureSpec)
        setMeasuredDimension(Math.min(width, height), Math.min(width, height))
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        mPath.apply {
            val h = ((width / 2.0) * sqrt(3.0)).toFloat()
            moveTo(width / 2f, 0f)
            lineTo(0f, h)
            lineTo(width.toFloat(), h)
            close()
        }
    }

    override fun onDraw(canvas: Canvas) {
        when (mCurrentShape) {
            Shape.Circle -> {
                // 画圆形
                val center = width / 2f
                mPaint.color = Color.parseColor("#aa738ffe")
                canvas.drawCircle(center, center, center, mPaint)
            }
            Shape.Square -> {
                // 画正方形
                mPaint.color = Color.parseColor("#aae84e40")
                canvas.drawRect(0f,0f,width.toFloat(),height.toFloat(), mPaint)
            }
            Shape.Triangle -> {
                // 画三角 Path 画路线
                mPaint.color = Color.parseColor("#aa72d572")
                canvas.drawPath(mPath, mPaint)
            }
        }
    }

    /**
     * 改变形状
     */
    fun exchange() {
        mCurrentShape = when (mCurrentShape) {
            Shape.Circle -> Shape.Square
            Shape.Square -> Shape.Triangle
            Shape.Triangle -> Shape.Circle
        }
        // 不断重新绘制形状
        invalidate()
    }

    fun getCurrentShape() = mCurrentShape
}